<template>
  <div class="app-container">
    <div class="filter-container">
      操作时间:<el-date-picker
          size="small"
          class="filter-item"
          v-model="dateArr"
          type="daterange"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          value-format="yyyy-MM-dd"
          unlink-panels
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
      ></el-date-picker>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" size="small">搜索
      </el-button>
    </div>
    <el-table
        v-loading="listLoading"
        :data="list"
        :row-class-name="tableRowClassName"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
    >
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="对账周期开始时间">
        <template slot-scope="scope">
          {{ scope.row.start_at }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="对账周期结束时间">
        <template slot-scope="scope">
          {{ scope.row.end_at }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="锦江成本总额">
        <template slot-scope="scope">
          {{ scope.row.jin_jiang_total_cost }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="对账成本总额">
        <template slot-scope="scope">
          {{ scope.row.system_total_cost }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="对账销售结算总额">
        <template slot-scope="scope">
          {{ scope.row.channel_total_money }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="对账结果">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.result_type == 1" type="success">符合</el-tag>
          <el-tag v-else type="warning">不符合</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作时间">
        <template slot-scope="scope">
          {{ scope.row.created_at }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作人员">
        <template slot-scope="scope">
          {{ scope.row.admin?scope.row.admin.username:"-" }}
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <download-excel
              class="filter-item"
              :fields="json_fields2"
              :fetch="() =>handleExport2(scope.row.id)"
              type="xls"
              name="订单对账.xls"
              worksheet="订单对账"
          >
            <el-button
                size="mini"
                type="success"
                :loading="exportLoadingMap[scope.row.id] === true"
                @click="userLogsid = scope.row.id"
            >
              下载Excel
            </el-button>
          </download-excel>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
        title="导入订单对账"
        :visible.sync="showaddLog"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        append-to-body
        width="512px"
    >
      <el-form
          ref="addLogform"
          :model="addLogform"
          :rules="addLogRules"
          label-width="0px"
      >
        <el-form-item>
          <el-date-picker
              v-model="addLogform.date"
              type="datetimerange"
              @change="changeaddLogformdata"
              format="yyyy-MM-dd hh:mm:ss"
              value-format="yyyy-MM-dd hh:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-row type="flex">
          <el-col :span="8">
            <el-upload
                class="filter-item"
                accept=".xlsx,.xls"
                action=""
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleImportUsers"
            >
              <el-button type="warning" icon="el-icon-upload" size="small">
                订单对账导入
              </el-button>
            </el-upload>
          </el-col>
          <el-button
              class="filter-item"
              type="primary"
              @click="downloadExcel"
              size="small"
          >
            下载订单对账模板
          </el-button>
        </el-row>
        <div style="height: 500px" class="scrollbar">
          <el-scrollbar style="height: 500px">
            <el-table :data="addLogform.jin_jiang_orders" style="width: 1100px">
              <el-table-column label="锦江订单号" min-width="60" align="center">
                <template slot-scope="scope">
                  {{ scope.row.order_code || '' }}
                </template>
              </el-table-column>
              <el-table-column label="锦江支付总价" min-width="60" align="center">
                <template slot-scope="scope">
                  {{ scope.row.total_rate || '' }}
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
        <el-row type="flex" justify="end">
          <el-button @click="showaddLog = false">取消</el-button>
          <el-button type="primary" @click="postaddLog">确认</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import downloadExcel from 'vue-json-excel'
import {excel2Json} from '@/utils/excel'

export default {
  components: {downloadExcel},
  data() {
    return {
      showaddLog: false,
      addLogRules: {
        reason: [
          {required: true, message: '请填写驳回理由', trigger: 'blur'},
        ],
      },
      addLogform: {
        users: [],
        date: '',
        start_date: '',
        end_date: '',
      },
      list: null,
      total: null,
      listLoading: false,
      exportLoading: false,
      exportLoadingMap: {},
      listQuery: {
        page: 1,
        limit: 10,
        start_at: '',
        end_at: '',
      },
      userLogsid: '',
      viplist: [],
      json_fields: {
        发放人数: {
          field: 'user_num',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        发放时间: {
          field: 'created_at',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
      },
      json_fields2: {
        锦江订单号: {
          field: 'order_code',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        锦江成本金额: {
          field: 'jin_jiang_cost',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        对账成本金额: {
          field: 'system_cost',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        对账销售总额: {
          field: 'channel_money',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
      },
      dateArr: null,
    }
  },
  created() {
    this.getList()
  },
  watch: {
    showaddLog() {
      this.addLogform = {
        jin_jiang_orders: [],
        date: '',
        end_travel_date_start_at: '',
        end_travel_date_end_at: '',
      }
    },
    dateArr(newVal, oldVal) {
      if (newVal) {
        this.listQuery.start_at = newVal[0];
        this.listQuery.end_at = newVal[1];
      } else {
        this.listQuery.start_at = "";
        this.listQuery.end_at = "";
      }
    },
  },
  computed: {
    //状态：none：未处理 ； pending：处理中 ；completed：已完成； revoke_pending ：撤销处理中；revoked：已撤销
    status() {
      return (val) => {
        switch (val) {
          case 'none':
            return '未处理'
          case 'pending':
            return '处理中'
          case 'completed':
            return '已完成'
          case 'revoke_pending':
            return '撤销处理中'
          case 'revoked':
            return '已撤销'
        }
      }
    },
    revenue_type() {
      return (val) => {
        switch (val) {
          case 'retail_bonus':
            return '零售奖励'
          case 'referral_bonus':
            return '推荐奖励'
          case 'distribution_bonus':
            return '分销奖励'
          case 'expansion_bonus':
            return '级差奖励'
          case 'welfare_bonus':
            return '福利奖励'
          case 'founder_bonus':
            return '创始人分红'
          case 'vip_bonus':
            return 'VIP 分红'
          case 'super_vip_bonus':
            return '钻石分红'
        }
      }
    },
  },
  methods: {
    tableRowClassName({row}) {
      const systemCost = Number(row.system_cost);
      const jinJiangCost = Number(row.jin_jiang_cost);

      if (systemCost === 0) {
        console.log(systemCost);
        return 'row-red';
      }

      if (jinJiangCost === 0) {
        return 'row-blue';
      }

      if (systemCost > 0 && jinJiangCost > 0 && systemCost !== jinJiangCost) {
        return 'row-yellow';
      }

      return '';
    },

    addLog() {
      this.showaddLog = true
    },
    downloadExcel() {
      let a = document.createElement('a')
      a.href = '/订单对账模板.xlsx'
      a.download = '订单对账模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    postaddLog() {
      if (!this.addLogform.end_travel_date_start_at || !this.addLogform.end_travel_date_end_at) {
        this.$message.warning('请选择开始与结束日期')
        return
      }
      return request({
        url: '/api/backend/reconciliation-log/create-log',
        method: 'POST',
        data: this.addLogform,
      })
          .then((res) => {
            if (res.code == 0) {
              this.$message({
                type: 'success',
                message: '操作成功',
              })
              this.showaddLog = false
              this.list = res.data
              this.total = res.data.length
            }
          })
          .finally((val) => {
            console.log(val)
          })
    },
    handleImportUsers(file) {
      this.addLogform.users = []
      file = file.raw
      if (
          !(file.name.split('.')[1] == 'xlsx' || file.name.split('.')[1] == 'xls')
      ) {
        this.$message.error('上传文件格式不正确，请检查选择的文件')
        return
      }
      excel2Json(file, 1).then((excelData) => {
        console.log(excelData)
        // 处理业务
        if (excelData.length <= 0) {
          this.$message.error('数据不能为空')
          return
        }
        excelData.forEach((element, index) => {
          if (element['锦江订单号']) {
            this.addLogform.jin_jiang_orders.push({
              order_code: element['锦江订单号'],
              total_rate: element['锦江支付总价'],
            })
          }
          console.log(element, '--------', index)
        })
        this.importDataDialogVisible = true
        console.log(this.addLogform.jin_jiang_orders, '=============')
      })
    },
    changedata(val) {
      console.log(val)
      if (val) {
        this.listQuery.start_at = val[0]
        this.listQuery.end_at = val[1]
      } else {
        this.listQuery.start_at = ''
        this.listQuery.end_at = ''
      }
    },
    changeaddLogformdata(val) {
      console.log(val)
      if (val) {
        this.addLogform.end_travel_date_start_at = val[0]
        this.addLogform.end_travel_date_end_at = val[1]
      } else {
        this.addLogform.end_travel_date_start_at = ''
        this.addLogform.end_travel_date_end_at = ''
      }
    },
    handleExport(id) {
      this.exportLoading = true
      var listQuery = JSON.parse(JSON.stringify(this.listQuery))
      return request({
        url: '/api/backend/reconciliation-log/detail',
        method: 'get',
        params: {
          id
        },
      })
          .then((response) => {
            console.log(response)
            return response.data
          })
          .finally((val) => {
            console.log(val)
            this.exportLoading = false
          })
    },
    handleExport2(id) {
      this.$set(this.exportLoadingMap, id, true);
      return request({
        url: '/api/backend/reconciliation-log/detail',
        method: 'get',
        params: {
          id
        },
      })
          .then((response) => {
            console.log(response)
            return response.data.orders
          })
          .finally((val) => {
            console.log(val)
            this.$set(this.exportLoadingMap, id, false);
          })
    },
    getList() {
      this.listLoading = true
      this.listQuery.start_at = this.listQuery.start_at + " 00:00:00"
      this.listQuery.end_at = this.listQuery.end_at + " 23:59:59"
      request({
        url: '/api/backend/reconciliation-log/list',
        method: 'get',
        params: this.listQuery,
      }).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    revoke(row) {
      this.$confirm('是否确认撤销？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            request({
              url: '/api/backend/globalReward/revoke',
              method: 'post',
              data: {
                id: row.id,
              },
            }).then((res) => {
              console.log(res)
              if (res.code == 0) {
                this.$message({
                  type: 'success',
                  message: '操作成功',
                })
                this.getList()
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            })
          })
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 6px;
}

::v-deep .row-red {
  background-color: #ffecec !important;
}

::v-deep .row-blue {
  background-color: #e0f0ff !important;
}

::v-deep .row-yellow {
  background-color: #fffbe0 !important;
}
::v-deep .el-date-editor .el-range-separator{
  width: 8%;
}
</style>
